package com.amz.analyzer.keyword.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.amz.analyzer.exception.AmzException;
import com.amz.analyzer.google.trans.GTransApi;
import com.amz.analyzer.keyword.entity.SearchRank;
import com.amz.analyzer.keyword.req.SearchRankReq;
import com.amz.analyzer.keyword.service.ISearchRankService;
import com.amz.analyzer.keyword.vo.SearchRankVo;
import com.amz.analyzer.util.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Freddy
 * @since 2020-08-20
 */
@Slf4j
@Api(tags = "关键词搜索")
@RestController
@RequestMapping("/search-rank")
public class SearchRankController {

    @Autowired
    private ISearchRankService searchRankService;

    /**
     * 查询全部类型列表
     *
     * @return Result
     */
    @GetMapping(value = "/search")
    @ApiOperation(value = "/search", notes = "搜索关键词排名")
    public Result search(@Validated SearchRankReq searchRankReq) {

        IPage<SearchRank> pageData = searchRankService.search(searchRankReq);
        IPage<SearchRankVo> newPage = new Page<>(pageData.getCurrent(), pageData.getSize(),
                pageData.getTotal(), pageData.isSearchCount());

        List<String> keywordList = new ArrayList<>();
        List<SearchRankVo> resultList = pageData.getRecords().stream().map(item -> {
            SearchRankVo srv = new SearchRankVo();
            BeanUtils.copyProperties(item, srv);
            if (searchRankReq.getShowChinese() == 1) {
                keywordList.add(item.getKeyword());
            }
            return srv;
        }).collect(Collectors.toList());

        if (searchRankReq.getShowChinese() == 1) {

            String splitTag = StrUtil.CRLF;
            StringBuffer query = new StringBuffer();
            for (int i = 0; i < keywordList.size(); i++) {
                String kword = keywordList.get(i);
                if (kword.length() >= 295) {
                    kword = kword.substring(0, 295);
                }
                kword = kword.replace(StrUtil.DOT, "。");
                query.append(kword);
//                query.append(StrUtil.SPACE+splitTag+StrUtil.SPACE);
                query.append(splitTag);
            }


            String transResult = GTransApi.translateSingle(query.toString());
//            log.debug(transResult);
            JSONObject jsonObject = JSONUtil.parseObj(transResult);
            JSONArray sentencesArray = jsonObject.getJSONArray("sentences");

            if (resultList.size() != sentencesArray.size()) {
                log.warn(StrUtil.format("翻译前个数:{}，翻译后个数:{}", resultList.size(), sentencesArray.size()));
                throw new AmzException("翻译结果个数错误！");
            }

            for (int i = 0; i < resultList.size(); i++) {
                SearchRankVo vo = resultList.get(i);
                JSONObject jsonObj = (JSONObject) sentencesArray.get(i);
                String trans = jsonObj.getStr("trans", StrUtil.EMPTY);
//                String orig = jsonObj.getStr("orig", StrUtil.EMPTY); //原始因为，暂时不用
                vo.setChineseKeyWord(trans);
            }
        }

        newPage.setRecords(resultList);
        return Result.success(newPage);
    }

    /**
     * 获取（统计）日期列表
     *
     * @return 统计日期列表
     */
    @GetMapping(value = "/stat-date-list")
    @ApiOperation(value = "/stat-date-list", notes = "获取（统计）日期列表")
    public Result getStatDateList() {

        return Result.success(searchRankService.getStatDateList());
    }

}

